package ray.mgocc.net;

import ray.mgocc.PlayerCharacter;
import ray.mgocc.Source;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.ArrayList;
import java.util.List;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CommunitySupportPage{
    private final static Log log = LogFactory.getLog(CommunitySupportPage.class);
    final static String LOCALE = "jp";
    final static String LANG = "us";
    final static String RESOLUTION = "sd";
    private GameAccount account;
    private PlayerSelectPage psp = null;
    final static String URI = "http://mgo2sns.konamionline.com/"+LOCALE+"/community/";
    private Agent agent;
    public CommunitySupportPage(Agent agent,GameAccount account){
        this.agent = agent;
        this.account = account;
    }
    public void init(){
        List<String> pre = new ArrayList<String>();
        pre.add(URI);
        pre.add(URI+"?m=pc&a=page_o_agree&lang="+LANG+"&resolution="+RESOLUTION);
        pre.add(URI+"?m=pc&a=do_o_agree_check&agreement=1");
        for(String uri:pre){
            agent.get(uri);
        }

        Properties login = new Properties();
        login.setProperty("m","pc");
        login.setProperty("a","do_o_pre_login");
        login.setProperty("username",account.getId());
        login.setProperty("password",account.getPassword());
        agent.post(URI,login);

        Source playerSelectPage = null;
        try{
            playerSelectPage = agent.get(URI+"?m=pc&a=page_o_select_player");
            this.psp = new PlayerSelectPage(new InputStreamReader(playerSelectPage.getStream()));
        }finally{
            if(null!=playerSelectPage){
                playerSelectPage.close();
            }
        }
    }
    public PlayerCharacter select(){
        return select(0);
    }
    public PlayerCharacter select(int index){
        if(0==getPlayerCharacters().size()){
            throw new RuntimeException("Can not find own PC.");
        }
        for(PlayerCharacter me:getPlayerCharacters()){
            log.debug(me.toString());
        }
        PlayerCharacter pc = psp.getPlayerCharacters().get(index);
        agent.get(URI+"?m=pc&a=do_o_select_player&pid="+pc.getNumber());
        return pc;
    }

    public List<PlayerCharacter> getPlayerCharacters(){
        if(null == psp){
            init();
        }
        return psp.getPlayerCharacters();
    }
    private void memo(){
        String resolution;
        resolution = "hd";
        resolution = "sd";

        String act;
        act = "page_o_top";
        act = "page_o_agree";
        act = "do_o_agree_check";
        act = "page_o_login";
        act = "do_o_pre_login";
        act = "page_o_select_player";
        act = "do_o_select_player";
    }
}
